//
// Created by Jeffrey Wei on 2022/11/2.
//

import Foundation
import Moya
import RxSwift

private var providers = [String: Any]()

extension NetworkTargetType {
    // 每种不同类型的TargetType在内部会有一个唯一的provider
    static var provider: MoyaProvider<Self> {
        let key = String(describing: type(of: self))
        if let provider = getProvider(key: key) as? MoyaProvider<Self> {
            return provider
        }
        // 解析插件,主要是解析结果,返回数据的data
        let parsingPlugin = NetworkParsingPlugin()
        // token插件
        let accessTokenPlugin = AccessTokenPlugin {
            let token = ($0 as? NetworkTargetType)?.accessToken?.value ?? ""
            return token
        }
        // 日志插件
        let loggerPlugin = NetworkLoggerDefaultPlugin()
        // 默认插件数组
        let plugins: [PluginType] = [parsingPlugin, accessTokenPlugin, loggerPlugin]
        let provider = MoyaProvider<Self>.init(plugins: plugins)
        registerProvider(key: key, provider: provider)
        return provider
    }
}

extension NetworkTargetType {
    private static func registerProvider(key: String, provider: Any) {
        guard providers[key] == nil else { return }
        providers[key] = provider
    }

    private static func getProvider(key: String) -> Any? {
        guard let provider = providers[key] else { return nil }
        return provider
    }
}
